package com.android.camera.one.v2.initialization;

import java.util.List;

import com.android.camera.debug.Log;
import com.android.camera.one.FaceDetectInfo;
import com.android.camera.one.OneCamera;
import com.android.camera.one.OneCamera.FaceDetectListener;
import com.android.camera.one.OneCamera.Facing;
import com.android.camera.one.OneCamera.IMetadataResult;
import com.android.camera.one.OneCamera.MetadataListener;
import com.android.camera.one.OneCameraCharacteristics;
import com.android.camera.util.Size;

import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.params.Face;

public class FilteredFaceUpdate implements MetadataListener {
	private static final Log.Tag TAG = new Log.Tag("FilteredFaceUpdate");
	private final FaceDetectListener mFaceDetectListener;
	private OneCamera.Facing mFacing;
	private int mOrientation;
	final int dX, dY, offX, offY;
	
	public FilteredFaceUpdate(OneCameraCharacteristics characteristics, FaceDetectListener faceDetectListener) {
		List<Size> pictureSizes = characteristics.getAllSupportedPictureSizes(ImageFormat.YUV_420_888);
		mOrientation = characteristics.getSensorOrientation();
		mFacing = characteristics.getCameraDirection();
		Size largestYuvSize = returnLargestSize(pictureSizes);
		Rect activeArea = characteristics.getSensorInfoActiveArraySize();
		offX = (activeArea.width() - largestYuvSize.width()) / 2;
		offY = (activeArea.height()- largestYuvSize.height())/ 2;
		dX   = activeArea.width() - 2 * offX;
		dY   = activeArea.height()- 2 * offY;
		mFaceDetectListener = faceDetectListener;
	}

	@Override
	public void onMetadataCallback(IMetadataResult result) {
		Face[] faces = result.get(CaptureResult.STATISTICS_FACES);
		if (faces == null) {
			return;
		}
		Log.d(TAG, "update "+faces.length);
		FaceDetectInfo[] faceInfo = new FaceDetectInfo[faces.length];
		for (int i = 0; i < faces.length; i++) {
			faceInfo[i] = FaceDetectInfo.generate(faces[i], mFacing == Facing.FRONT, 
					dX, dY, offX, offY, mOrientation);
		}
		mFaceDetectListener.onFaceDetectCallback(faceInfo);
	}
	
	private Size returnLargestSize(List<Size> sizes) {
        Size largestSize = null;
        int area = 0;
        for (int j = 0; j < sizes.size(); j++) {
            if (sizes.get(j).getHeight() * sizes.get(j).getWidth() > area) {
                area = sizes.get(j).getHeight() * sizes.get(j).getWidth();
                largestSize = sizes.get(j);
            }
        }
        return largestSize;
    }
}
